package ink.tiptop.exception;

import ink.tiptop.common.domain.rsp.FailedResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author ink.tiptop.zjf
 * @Title: Ticket
 * @Package ink.tiptop.exception
 * @Description: 全局异常处理捕获处理, 返回
 * @date 2020-07-15 09:26
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Object paramCheckExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        return new FailedResponse(400, getErrors(bindingResult));
    }

    private String getErrors(BindingResult result) {
        return result.getFieldErrors().stream().map(lst -> lst.getDefaultMessage()).collect(Collectors.joining(","));
    }

    @ExceptionHandler(value = { MethodArgumentNotValidException.class })
    @ResponseBody
    public Object methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String errors = getErrors(ex.getBindingResult());
        int length = errors.length();
        return new FailedResponse(400, errors.substring(0,length>50?50:length));
    }

    @ExceptionHandler(value = { Exception.class })
    @ResponseBody
    public Object exception(Exception ex) {
        log.error(ex.getMessage(), ex);
        return new FailedResponse(400, "未知异常");
    }

    @ExceptionHandler(value = { BaseException.class })
    @ResponseBody
    public Object runtimeException(BaseException ex) {
        return new FailedResponse(ex.getMsg().getCode(), ex.getMsg().getMsg());
    }

}
